#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2024/3/19 17:34
# @Author : Carey
# @File : dashbord.py
# @Description

from flask import Blueprint
from Flask.app.Models.Sites import Sites
from Flask.app.Models.Users import Users
from flask import render_template
from flask import request
from flask import redirect
from flask import url_for
from flask import json
from flask import make_response
from flask import abort
import jsonify


### 初始化 Blueprint
bp = Blueprint( 'dashbord', __name__, url_prefix='/' )


"""
System Index
后端数据传递 - 多参数传递视图 , 分割
"""
@bp.route( '/index', methods=['GET'] )
@bp.route( '/', methods=['GET'] )
def dashbord():
    data = {
        'uid': 1,
        'uname': "Carey"
    }

    ### 添加
    # ftime = time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime() )
    # site = Sites(created_at=ftime, updated_at=ftime, name='www.google.com', email='google@qq.com', phone='+86 15032250258', remarks='www.google.com')
    # db.session.add( site )
    #db.session.commit()

    #关联取数据
    user = Users.query.get(1)
    print( user )
    sites = user.sites.all()
    for item in sites :
        print( f"站点编号：{item.id}, 站点名称：{item.name}, 创建人：{item.user.name}, 站点邮件：{item.email}, 站点电话：{item.phone}, 创建时间：{item.created_at}")

    ### 查找
    #### get 主键查找
    site = Sites.query.get(1)
    print( f"站点编号：{site.id}, 站点名称：{site.name}, 创建人：{site.user.name}, 站点邮件：{site.email}, 站点电话：{site.phone}, 创建时间：{site.created_at}" )

    #### filter_by
    # sites = Sites.query.filter_by( name='www.google.com' )
    #print(f"站点编号：{site.id}, 站点名称：{site.name}, 站点邮件：{site.email}, 站点电话：{site.phone}, 创建时间：{site.created_at}")
    # for item in sites:
    #     print(f"站点编号：{item.id}, 站点名称：{item.name}, 站点邮件：{item.email}, 站点电话：{item.phone}, 创建时间：{item.created_at}")

    ### 修改
    # site.email='email@google.com'
    # db.session.commit()
    #
    # ### 删除
    # site = Sites.query.get(7)
    # db.session.delete( site )
    # db.session.commit()

    return render_template( 'index.html', user = data )


# segment
# <string:arg>    字符串
# <int:arg>       整数
# <float:arg>     浮点
# <path:arg>      路径

@bp.route( '/user/<uid>', methods=['GET'] )
def user( uid ):
    id = int( uid )

    # 关联取数据
    user = Users.query.get( id )
    data = {
        'id': user.id,
        'name': user.name,
        'email': user.email,
        'created_at': user.created_at,
        'updated_at': user.updated_at,
    }

    return make_response( data )



# """
# 相应  response
# text
# json
# """
@bp.route( '/user/list', methods=['GET'] )
def list():

    # 关联取数据
    users = Users.query.all()

    data = {
        'uid': 1,
        'uname': "Carey"
    }

    return render_template( 'users.html', user = data, list = users )


# """
# Render Template
# """
@bp.route( '/user/create', methods=['GET'] )
def create():
    return render_template( 'create.html' )



# '''
# 前后端交互
# request 对象
# '''
@bp.route( '/user/save', methods=[ 'GET', 'POST' ] )
def save():
    if 'GET' == request.method:
        uname = request.args.get('uname')
        uage = request.args.get('uage')
        uemail = request.args.get('uemail')

        respData = {
            'id': round( 100,1000 ),
            'name': uname,
            'age': uage,
            'email': uemail
        }
        return make_response(respData)

    if 'POST' == request.method:
        uname = request.form.get('uname')
        uage = request.form.get('uage')
        uemail = request.form.get('uemail')

        respData = {
            'id':  round( 100,1000 ),
            'name': uname,
            'age': uage,
            'email': uemail
        }
        return make_response( respData )

# queryString
@bp.route( '/room/<rname>', methods=['GET'] )
def getRoom( rname ):
    return f"Hi~ Jobs, Welcom Rome {rname}"



# """
# 重定向
# redirect    - 外部跳转
# url_for     - 内部跳转
# """
@bp.route( '/redirt/<type>', methods=['GET'] )
def redirt( type ):
    if 'baidu' == type:
        return redirect( 'https://www.baidu.com' )

    if 'google' == type:
        return redirect( 'https://www.google.com' )

    if 'self' == type:
        return redirect( url_for( 'dashbord.dashbord' ) )




# """
# raise
# abort 在网页中主动抛出异常
# """
@bp.route( '/user/disab', methods=["GET"] )
def disab():
    abort( '500' )
    return redirect( url_for( 'list' ) )